package net.sumcraft.pointconvert;

import org.bukkit.ChatColor;
import org.bukkit.entity.Player;


/**
 * Created by zhen on 2017/6/30.
 */
public class ConvertPointsRunnable implements Runnable {
    private Player player;
    private String checkURL;
    private String deductURL;
    private String strKey;
    private int points = 0;

    //构造函数
    public ConvertPointsRunnable(Player player, String strKey, String url) {
        this.player = player;
        this.strKey = strKey;
        this.deductURL = String.valueOf(url) + "deduct";
        this.checkURL = String.valueOf(url) + "cardinfo";
    }

    @Override
    public void run() {
        try {
            String s1 = HttpRequest.sendGet(checkURL, strKey);
            if (s1 != null) {
                String[] str1 = s1.split("&");
                if (str1[1].equalsIgnoreCase("1001")) {
                    player.sendMessage(ChatColor.RED + "查询失败: 插件内部错误，提交参数不全");
                } else if (str1[1].equalsIgnoreCase("1002")) {
                    player.sendMessage(ChatColor.RED + "查询失败: 服务器IP设置错误");
                } else if (str1[1].equalsIgnoreCase("2002")) {
                    points = Integer.parseInt(str1[2]);
                } else {
                    player.sendMessage(ChatColor.RED + "无法解析");
                }
            }
            if (points > 0) {
                strKey = strKey + "&money=" + String.valueOf(points);
                String s2 = HttpRequest.sendGet(deductURL, strKey);
                String[] str2 = s2.split("&");
                if (str2[1].equalsIgnoreCase("1001")) {
                    player.sendMessage(ChatColor.RED + "消费失败: 插件内部错误，提交参数不全");
                } else if (str2[1].equalsIgnoreCase("1002")) {
                    player.sendMessage(ChatColor.RED + "消费失败: 服务器IP设置错误");
                } else if (str2[1].equalsIgnoreCase("1003")) {
                    player.sendMessage(ChatColor.RED + "消费失败: 余额不足！当前余额" + ChatColor.YELLOW + str2[2] + ChatColor.GREEN + " 点。");
                } else if (str2[1].equalsIgnoreCase("2001")) {
                    player.sendMessage(ChatColor.GREEN + "消费成功！当前余额" + ChatColor.YELLOW + str2[2] + ChatColor.GREEN + " 点。");
                    PointConvert.playerPoints.getAPI().give(player.getUniqueId(),Integer.parseInt(str2[2]));
                    player.sendMessage(ChatColor.GREEN+"成功转换"+ChatColor.RED+str2+ChatColor.GREEN+"点券, 当前晶石为: "
                            +ChatColor.RED+PointConvert.playerPoints.getAPI().look(player.getUniqueId())+ChatColor.GREEN+"枚");
                }
            }

        } catch (Exception e) {
            this.player.sendMessage(ChatColor.RED + "通讯故障, 请稍候再试");
        }
    }
}